package com.patrrr.Note;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.DatePickerDialog.OnDateSetListener;
import android.appwidget.AppWidgetManager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.Contacts.ContactMethods;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker.OnTimeChangedListener;

import com.patrrr.SQLite3.DBHandler;
import com.patrrr.SQLite3.DBHelper;
import com.patrrr.Widget.NoteWidget;
import com.patrrr.app.Background;
import com.patrrr.app.NoteInfo;
import com.patrrr.util.Alert;
import com.patrrr.util.Configuration;
import com.patrrr.util.Reminder;
import com.patrrr.Note.R;

public class NoteEditor extends Activity {
	// 标签背景
	private ImageView bg;
	// 编辑区
	private EditText edit;

	// title
	private LinearLayout title; // 布局
	private TextView title_createTime; // 创建时间
	private ImageView title_alertClock; // 闹钟提示图标
	private TextView title_alertTime; // 闹钟提示倒计时
	private ImageView title_color; // 取色按钮

	// 取色板
	private LinearLayout color; // 布局
	private ImageView color_yellow; // 黄色
	private ImageView color_pink; // 粉红
	private ImageView color_blue; // 蓝色
	private ImageView color_green; // 绿色
	private ImageView color_gray; // 灰色

	// 字体大小调整
	private LinearLayout textSize; // 布局
	private SeekBar sizeBar; // seekBar
	private int fontSize; // 字体大小

	// 日期相关
	private TimePicker mTimePicker;
	private String[] array_dayOfWeek = new String[] { "星期日", "星期一", "星期二",
			"星期三", "星期四", "星期五", "星期六" };
	// 提醒时间相关
	private int alertYear;
	private int alertMonth; // 0--11
	private int alertDay;
	private int alertHour;
	private int alertMinute;

	private int mYear; // 当前 年
	private int mMonth; // 当前 月 0--11
	private int mDay; // 当前 日
	private int mDayOfWeek; // 当前 星期 1--7对应 星期日--星期一--..--星期六

	private Button remind_dateButton;

	// note
	private NoteBean mNoteBean;

	// 颜色代号
	private static final int YELLOW = 0;
	private static final int PINK = 1;
	private static final int BLUE = 2;
	private static final int GREEN = 3;
	private static final int GRAY = 4;

	// AlertDialog
	private static final int DIALOG_ALERT = 0;
	private static final int DIALOG_DELETE = 1;
	private static final int DIALOG_CHANGEDATE = 2;

	private String mode;
	public static final String MODE_CREATE_NOTE = "modeCreateNote";
	public static final String MODE_CREATE_WIDGET = "android.appwidget.action.APPWIDGET_CONFIGURE";
	public static final String MODE_VIEW_NOTE = "modeViewNote";
	public static final String MODE_VIEW_WIDGET = "modeViewWidget";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.note_editor);

		Configuration configuration = new Configuration(this);
		fontSize = configuration.getInt(Configuration.FONTSIZE, 16);
		mode = getIntent().getAction();
		if (mode != null) {

		}
		// 新建或查看便签
		if (mode.equals(MODE_CREATE_NOTE) || mode.equals(MODE_VIEW_NOTE)) {
			mNoteBean = (NoteBean) getIntent().getSerializableExtra(
					NoteInfo.NOTE_BEAN);
		}
		// 查看widget
		if (mode.endsWith(MODE_VIEW_WIDGET)) {
			Bundle bundle = getIntent().getExtras();
			if (bundle != null) {
				mNoteBean = (NoteBean) bundle
						.getSerializable(NoteInfo.NOTE_BEAN);
			}
		}
		// 新建widget
		if (mode.equals(MODE_CREATE_WIDGET)) {
			mNoteBean = new NoteBean();
			mNoteBean.setFolderId(-1);
			mNoteBean.setContent("");
			mNoteBean.setCreateTime(Calendar.getInstance().getTimeInMillis());
			mNoteBean.setAlertTime(0);
			mNoteBean.setColor(configuration
					.getInt(Configuration.COLOR, YELLOW));

			Bundle bundle = getIntent().getExtras();
			if (bundle != null) {
				int widgetId = bundle.getInt(
						AppWidgetManager.EXTRA_APPWIDGET_ID,
						AppWidgetManager.INVALID_APPWIDGET_ID);
				mNoteBean.setWidgetId(widgetId);
			}
		}

		if (mNoteBean == null) {
			mNoteBean = new NoteBean();
			mNoteBean.setFolderId(-1);
			mNoteBean.setContent("");
			mNoteBean.setCreateTime(Calendar.getInstance().getTimeInMillis());
			mNoteBean.setAlertTime(0);
			mNoteBean.setColor(0);
			mNoteBean.setWidgetId(0);
			System.out.println("bean null");
		}

		bg = (ImageView) findViewById(R.id.editor_bg);

		title = (LinearLayout) findViewById(R.id.editor_title);
		title_createTime = (TextView) findViewById(R.id.editor_title_time);
		title_alertClock = (ImageView) findViewById(R.id.editor_title_alertClock);
		title_alertTime = (TextView) findViewById(R.id.editor_title_alertTime);
		title_color = (ImageView) findViewById(R.id.editor_title_color);

		title_color.setOnClickListener(colorListener);

		title_createTime.setText(getDateStr(mNoteBean.getCreateTime())); // -----------显示创建时间
		refreshTitleAlert(mNoteBean.getAlertTime());

		edit = (EditText) findViewById(R.id.editor_edit);
		edit.setOnClickListener(editListener);

		textSize = (LinearLayout) findViewById(R.id.editor_textSize);

		sizeBar = (SeekBar) textSize.findViewById(R.id.editor_textsize_seekBar);
		sizeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				int value = seekBar.getProgress();
				fontSize = value + 10;
				saveFontSize(fontSize);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				edit.setTextSize(progress + 10);
			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setColor(mNoteBean.getColor());
		edit.setTextSize(fontSize);
		edit.setText(mNoteBean.getContent());
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		int folderId = mNoteBean.getFolderId();
		String content = edit.getText().toString();
		long createTime = mNoteBean.getCreateTime();
		long alertTime = mNoteBean.getAlertTime();
		int color = mNoteBean.getColor();
		int widgetId = mNoteBean.getWidgetId();
		saveFontSize(fontSize);
		saveBg(color);
		saveNote(mode, folderId, content, createTime, alertTime, color,
				widgetId);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private void refreshTitleAlert(long alertTime) {
		if (alertTime == 0) {
			title_alertClock.setVisibility(View.GONE);
			title_alertTime.setVisibility(View.GONE);
		} else {
			title_alertClock.setVisibility(View.VISIBLE);
			title_alertTime.setVisibility(View.VISIBLE);
			title_alertTime.setText(getAlertTimeStr(alertTime));
		}
	}

	/**
	 * 获取日期字符串
	 * 
	 * @param timeInMillis
	 * @return
	 */
	private String getDateStr(long timeInMillis) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(timeInMillis);
		int y = calendar.get(Calendar.YEAR);
		int m = calendar.get(Calendar.MONTH) + 1; // month 从0开始
		int d = calendar.get(Calendar.DAY_OF_MONTH);
		int h = calendar.get(Calendar.HOUR_OF_DAY);
		int mi = calendar.get(Calendar.MINUTE);
		String m_s = m < 10 ? "0" + m : "" + m;
		String h_s = h < 10 ? "0" + h : "" + h;
		String mi_s = mi < 10 ? "0" + mi : "" + mi;

		StringBuffer date = new StringBuffer();

		date.append(m_s + getString(R.string.month));
		date.append(String.valueOf(d) + getString(R.string.day) + " ");
		date.append(h_s + ":" + mi_s);
		return date.toString();
	}

	/**
	 * 获取显示剩余提醒时间字符串
	 * 
	 * @param alertTime
	 */
	private String getAlertTimeStr(long alertTime) {
		StringBuffer time = new StringBuffer();
		Calendar calendar = Calendar.getInstance();
		long millis_cur = calendar.getTimeInMillis();
		long remain = (alertTime - millis_cur) / 1000;
		if (remain <= 0) {
			return getString(R.string.alterOver);
		}
		if (remain < (60)) { // 不足一分钟
			time.append(getString(R.string.lessThanOneMinute));
			return time.toString();
		}
		long m;
		if (remain < 60 * 60) { // 不到一个小时
			m = remain / 60;
			time.append(m + getString(R.string.alertAfterMinutes));
			return time.toString();
		}
		long h;
		if (remain < 60 * 60 * 24) { // 不到一天
			h = remain / (60 * 60);
			time.append(h + getString(R.string.alertAfterHours));
			return time.toString();
		}
		long d;
		// 超过一天
		d = remain / (60 * 60 * 24);
		time.append(d + getString(R.string.alertAfterDays));
		return time.toString();
	}

	/**
	 * 保存Note数据
	 * 
	 * @param folderName
	 *            保存至
	 * @param content
	 *            内容
	 * @param time
	 *            保存时间
	 * @param alertTime
	 *            提醒时间。未设提醒时间则为0；
	 */
	private void saveNote(String action, int folderId, String content,
			long createTime, long alertTime, int color, int widgetId) {
		DBHandler dbHandler = new DBHandler(this);
		if (action.equals(MODE_CREATE_NOTE)
				|| action.equals(MODE_CREATE_WIDGET)) {
			if (content.equals("") || content == null) {
				return;
			}
			ContentValues values = new ContentValues();
			values.put(DBHelper.NOTE_FOLDERID, folderId);
			values.put(DBHelper.NOTE_CONTENT, content);
			values.put(DBHelper.NOTE_CREATETIME, createTime);
			values.put(DBHelper.NOTE_ALERTTIME, alertTime);
			values.put(DBHelper.NOTE_COLOR, color);
			values.put(DBHelper.NOTE_WIDGETID, widgetId);
			dbHandler.insert(DBHelper.NOTE, values);
			dbHandler.close();
		} else if (action.equals(MODE_VIEW_NOTE)) {
			if (content.equals("") || content == null) {
				dbHandler.delete(DBHelper.NOTE, mNoteBean.getId());
			} else {
				ContentValues values2 = new ContentValues();
				values2.put(DBHelper.NOTE_CONTENT, content);
				values2.put(DBHelper.NOTE_CREATETIME, createTime);
				values2.put(DBHelper.NOTE_ALERTTIME, alertTime);
				values2.put(DBHelper.NOTE_COLOR, color);
				dbHandler.update(DBHelper.NOTE, values2, mNoteBean.getId());
				dbHandler.close();
			}
		} else if (action.endsWith(MODE_VIEW_WIDGET)) {
			if (content.equals("") || content == null) { // 内容为空
				dbHandler.delete(DBHelper.NOTE, DBHelper.NOTE_WIDGETID + "=?",
						new String[] { "" + mNoteBean.getWidgetId() });
				dbHandler.close();
			} else {
				ContentValues values3 = new ContentValues();
				values3.put(DBHelper.NOTE_CONTENT, content);
				values3.put(DBHelper.NOTE_CREATETIME, createTime);
				values3.put(DBHelper.NOTE_ALERTTIME, alertTime);
				values3.put(DBHelper.NOTE_COLOR, color);
				values3.put(DBHelper.NOTE_WIDGETID, widgetId);

				dbHandler.update(DBHelper.NOTE, values3, DBHelper.NOTE_WIDGETID
						+ "=?", new String[] { mNoteBean.getWidgetId() + "" });
				dbHandler.close();
			}
		}
	}

	/**
	 * 保存Note背景
	 * 
	 * @param bg
	 */
	private void saveBg(int bg) {
		new Configuration(this).saveInt(Configuration.COLOR, bg);
	}

	/**
	 * 保存字体大小
	 * 
	 * @param fontSize
	 */
	private void saveFontSize(int fontSize) {
		new Configuration(this).saveInt(Configuration.FONTSIZE, fontSize);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.noteeditor_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.editor_menu_newNote:// 新建便签
			newEditor();
			break;
		case R.id.editor_menu_remind:// 提醒我
			showDialog(DIALOG_ALERT);
			break;
		case R.id.editor_menu_size:// 设置字体大小
			showFontSizeSeter();
			break;
		case R.id.editor_menu_delete:// 删除
			showDialog(DIALOG_DELETE);
			break;
		case R.id.editor_menu_checklist:// 进入清单模式
			break;
		case R.id.editor_menu_more:// 更多
			break;
		case R.id.editor_menu_more_desktop:// 更多-添加到桌面
			break;
		case R.id.editor_menu_more_share:// 更多-分享
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 转入NoteEditor
	 * 
	 */
	private void newEditor() {
		Intent i = new Intent(this, NoteEditor.class);
		NoteBean noteBean = new NoteBean();
		Configuration c = new Configuration(this);
		noteBean.setFolderId(mNoteBean.getFolderId());
		noteBean.setCreateTime(Calendar.getInstance().getTimeInMillis());
		noteBean.setColor(c.getInt(Configuration.COLOR, 0));
		noteBean.setWidgetId(0);
		i.setAction(MODE_CREATE_NOTE);
		i.putExtra(NoteInfo.NOTE_BEAN, noteBean);
		startActivity(i);
		finish();
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_ALERT:// 提醒我
			View remind = getLayoutInflater().inflate(R.layout.remind, null);
			remind_dateButton = (Button) remind
					.findViewById(R.id.editor_remind_bt);
			remind_dateButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					showDialog(DIALOG_CHANGEDATE);
				}
			});
			mTimePicker = (TimePicker) remind
					.findViewById(R.id.editor_remind_timePicker);
			mTimePicker.setIs24HourView(true);
			mTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {

				@Override
				public void onTimeChanged(TimePicker view, int hourOfDay,
						int minute) {
					// TODO Auto-generated method stub
					alertHour = hourOfDay;
					alertMinute = minute;
				}
			});
			return new AlertDialog.Builder(this).setTitle(R.string.remind)
					.setView(remind).setPositiveButton(R.string.OK,
							timeOKListener).setNegativeButton(
							R.string.CancelAlert, timeCancelListener).create();
		case DIALOG_DELETE: // 删除
			return new AlertDialog.Builder(this).setMessage(
					R.string.delete_warn).setPositiveButton(R.string.OK, null)
					.setNegativeButton(R.string.Cancel, null).create();
		case DIALOG_CHANGEDATE: // 更改日期
			return new DatePickerDialog(this, dateListener, mYear, mMonth, mDay);
		default:
			return super.onCreateDialog(id, args);
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_ALERT:
			Calendar calendar = Calendar.getInstance();
			mYear = calendar.get(Calendar.YEAR);
			mMonth = calendar.get(Calendar.MONTH); // 0--11
			mDay = calendar.get(Calendar.DAY_OF_MONTH);
			mDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // //从 1---7 对应
			// 星期日---星期一---...---星期六
			alertYear = mYear;
			alertMonth = mMonth;
			alertDay = mDay;
			alertHour = calendar.get(Calendar.HOUR_OF_DAY);
			alertMinute = calendar.get(Calendar.MINUTE);
			remind_dateButton.setText(mYear + "年" + (mMonth + 1) + "月" + mDay
					+ "日 " + array_dayOfWeek[mDayOfWeek - 1]);
			break;
		default:
			break;
		}
		super.onPrepareDialog(id, dialog, args);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// 拦截返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (textSize != null && textSize.isShown()) {
				textSize.setVisibility(View.GONE);
				return true;
			}
			if (color != null && color.isShown()) {
				color.setVisibility(View.GONE);
				return true;
			}
			if (mode.equals(MODE_CREATE_WIDGET)) {
				String content = edit.getText().toString();
				if (content.equals("") || content == null) {

				} else {
					mNoteBean.setContent(content);
					AppWidgetManager appWidgetManager = AppWidgetManager
							.getInstance(this);
					NoteWidget.WidgetUtil.updateWidget(this, appWidgetManager,
							mNoteBean, NoteEditor.class);
					Intent result = new Intent();
					result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
							mNoteBean.getWidgetId());
					setResult(RESULT_OK, result);
					finish();
				}
			}
			if (mode.endsWith(MODE_VIEW_WIDGET)) {
				String content = edit.getText().toString();
				mNoteBean.setContent(content);
				AppWidgetManager appWidgetManager = AppWidgetManager
						.getInstance(this);
				NoteWidget.WidgetUtil.updateWidget(this, appWidgetManager,
						mNoteBean, NoteEditor.class);
			}
		}
		// 拦截 menu 键
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (textSize != null && textSize.isShown()) {
				return true;
			}
			if (color != null && color.isShown()) {
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showColorSelector() {
		if (color == null) {
			color = (LinearLayout) findViewById(R.id.editor_color);
			color_yellow = (ImageView) findViewById(R.id.editor_color_yellow);
			color_pink = (ImageView) findViewById(R.id.editor_color_pink);
			color_blue = (ImageView) findViewById(R.id.editor_color_blue);
			color_green = (ImageView) findViewById(R.id.editor_color_green);
			color_gray = (ImageView) findViewById(R.id.editor_color_gray);

			color_yellow.setOnClickListener(colorListener);
			color_pink.setOnClickListener(colorListener);
			color_blue.setOnClickListener(colorListener);
			color_green.setOnClickListener(colorListener);
			color_gray.setOnClickListener(colorListener);
		}
		color.setVisibility(View.VISIBLE);
	}

	OnClickListener colorListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.editor_title_color: // title 取色图标
				if (color != null && color.isShown()) {
					color.setVisibility(View.GONE);
				} else {
					showColorSelector();
				}
				break;
			case R.id.editor_color_yellow: // 黄色
				setColor(YELLOW);
				break;
			case R.id.editor_color_pink: // 粉红
				setColor(PINK);
				break;
			case R.id.editor_color_blue: // 蓝色
				setColor(BLUE);
				break;
			case R.id.editor_color_green: // 绿色
				setColor(GREEN);
				break;
			case R.id.editor_color_gray: // 灰色
				setColor(GRAY);
				break;
			default:
				break;
			}
		}
	};

	private void setColor(int colorId) {
		if (colorId >= Background.editor_title_bg.length) {
			return;
		}
		mNoteBean.setColor(colorId);
		title.setBackgroundResource(Background.editor_title_bg[colorId]);
		bg.setBackgroundResource(Background.editor_edit_bg[colorId]);
		if (color != null && color.isShown()) {
			color.setVisibility(View.GONE);
		}
	}

	private void showFontSizeSeter() {
		textSize.setVisibility(View.VISIBLE);
		sizeBar.setProgress(fontSize - 10);
	}

	OnClickListener editListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (color != null && color.isShown()) {
				color.setVisibility(View.GONE);
			}
			if (textSize != null && textSize.isShown()) {
				textSize.setVisibility(View.GONE);
			}
		}
	};
	DialogInterface.OnClickListener timeOKListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Calendar calendar = Calendar.getInstance();
			calendar.set(alertYear, alertMonth, alertDay, alertHour,
					alertMinute);// remindMonth 1--12
			long alertTime = calendar.getTimeInMillis(); // 获取设定时间的毫秒数（1970年1月1日00:00:00
			// GMT至设定时间）
			Calendar calendar_cur = Calendar.getInstance();
			if (alertTime < calendar_cur.getTimeInMillis()) { // 设定时间小于当前时间
				Toast.makeText(NoteEditor.this, "不能设定当前时间", 1000).show();
			} else {
				Alert alert = new Alert(NoteEditor.this);
				alert.alertAtTime(alertTime, mNoteBean.getId());
				mNoteBean.setAlertTime(alertTime);
				refreshTitleAlert(alertTime);
			}
		}
	};
	DialogInterface.OnClickListener timeCancelListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			mNoteBean.setAlertTime(0);
			ContentValues values = new ContentValues();
			values.put(DBHelper.NOTE_ALERTTIME, 0);
			DBHandler dbHandler = new DBHandler(NoteEditor.this);
			dbHandler.update(DBHelper.NOTE, values, mNoteBean.getId());
			refreshTitleAlert(0);
			dbHandler.close();
			Alert alert = new Alert(NoteEditor.this);
			alert.cancelAlert(mNoteBean.getId());
		}
	};
	OnDateSetListener dateListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			alertYear = year;
			alertMonth = monthOfYear;
			alertDay = dayOfMonth;

			Calendar calendar = Calendar.getInstance();
			calendar.set(year, monthOfYear, dayOfMonth);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

			remind_dateButton.setText(year + "年" + (monthOfYear + 1) + "月"
					+ dayOfMonth + "日 " + array_dayOfWeek[dayOfWeek - 1]);
		}
	};
}
